package com.api.test;

import com.api.client.model.ApiLoginHandler;
import com.api.client.model.ApiProxyFactory;
import com.api.impl.RequestBuilderFactory;
import com.api.impl.ServiceApi;
import com.api.model.ApiRequestBuilder;
import com.api.model.OauthApi;

public class ApiScribeImpl extends ServiceApi implements OauthApi {

	private ApiLoginHandler loginHandler;

	public ApiScribeImpl(ApiLoginHandler loginHandler, ApiProxyFactory apiFactory, RequestBuilderFactory requestBuilderFactory) {
		super(apiFactory, requestBuilderFactory);
		if (loginHandler == null) {
			throw new IllegalArgumentException("LoginHandler cannot be null");
		}

		this.loginHandler = loginHandler;
	}

	@Override
	public void login(String username, String password) {

		loginHandler.login(username, password);
	}

	public void setAccess(String accessKey, String accessSecret) {

		loginHandler.setAccessKeys(accessKey, accessSecret);
	}

	@Override
	public String getAccessKey() {

		if (loginHandler.isLoggedIn()) {

			return loginHandler.getAccessKey();
		} else {
			throw new IllegalStateException("User is not logged in");
		}
	}

	@Override
	public String getAccessSecret() {
		if (!loginHandler.isLoggedIn()) {
			throw new IllegalStateException("User is not logged in");
		}
		return loginHandler.getAccessSecret();
	}

	@Override
	public boolean isLoggedIn() {
		return loginHandler.isLoggedIn();
	}

	public void signRequest(ApiRequestBuilder request) {
		if (!isLoggedIn()) {
			throw new IllegalStateException("User not logged in");
		}
		request.sign(getAccessKey(), getAccessSecret());
	}

	public <T> T send(ApiRequestBuilder request) throws Exception {
		if (!isLoggedIn()) {
			throw new IllegalStateException("User not logged in");
		}
		request.sign(getAccessKey(), getAccessSecret());
		return request.send();
	}
}
